import React, { useEffect, useRef } from 'react';
import { ROOM_BOUNDS, WALLS } from './walls';
import { miniState } from './minimapStore';

const Minimap: React.FC = () => {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  // pull state from global object each frame inside draw()

  useEffect(() => {
    const canvas = canvasRef.current!;
    const ctx = canvas.getContext('2d')!;
    const d = canvas.width; // square
    const radius = d / 2;

    let raf = 0;
    const draw = () => {
      ctx.clearRect(0, 0, d, d);
      // clip circle
      ctx.save();
      ctx.beginPath();
      ctx.arc(radius, radius, radius - 2, 0, Math.PI * 2);
      ctx.clip();

      // background
      ctx.fillStyle = 'rgba(0,0,0,0.6)';
      ctx.fillRect(0, 0, d, d);

      // scale
      const pad = 6;
      const sx = (d - pad * 2) / ROOM_BOUNDS.W;
      const sz = (d - pad * 2) / ROOM_BOUNDS.L;
      const s = Math.min(sx, sz);
      // 跟随模式：玩家居中
      const ox = radius - miniState.x * s;
      const oz = radius - miniState.z * s;

      // room rectangle
      ctx.strokeStyle = 'rgba(255,255,255,0.85)';
      ctx.lineWidth = 1.5;
      ctx.strokeRect(ox, oz, ROOM_BOUNDS.W * s, ROOM_BOUNDS.L * s);

      // walls
      ctx.strokeStyle = 'rgba(140,190,255,0.95)';
      ctx.lineWidth = 2;
      WALLS.forEach(w => {
        const x = ox + (w.cx - w.sx / 2) * s;
        const y = oz + (w.cz - w.sz / 2) * s;
        ctx.strokeRect(x, y, w.sx * s, w.sz * s);
      });

      // player position + heading triangle
      const cx = ox + miniState.x * s;
      const cz = oz + miniState.z * s;
      const len = 10;
      const vx = miniState.dx || 0;
      const vz = miniState.dz || 0;
      // normalize heading
      const mag = Math.hypot(vx, vz) || 1;
      const hx = (vx / mag) * len;
      const hz = (vz / mag) * len;
      // perpendicular for triangle base
      const px = -hz * 0.5;
      const pz =  hx * 0.5;
      ctx.fillStyle = '#00ffff';
      ctx.beginPath();
      ctx.moveTo(cx + hx, cz + hz);
      ctx.lineTo(cx + px, cz + pz);
      ctx.lineTo(cx - px, cz - pz);
      ctx.closePath();
      ctx.fill();

      ctx.restore();

      // circle border
      ctx.beginPath();
      ctx.arc(radius, radius, radius - 1, 0, Math.PI * 2);
      ctx.strokeStyle = 'rgba(255,255,255,0.8)';
      ctx.lineWidth = 2;
      ctx.stroke();

      // north indicator
      ctx.fillStyle = 'rgba(255,255,255,0.85)';
      ctx.font = '10px sans-serif';
      ctx.fillText('N', radius - 3, 12);

      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <canvas ref={canvasRef} width={140} height={140} style={{
      position: 'absolute', top: 12, right: 12, zIndex: 1001,
      borderRadius: 100, boxShadow: '0 2px 10px rgba(0,0,0,0.4)'
    }} />
  );
};

export default Minimap;
